package com.briup.searchengine.handle;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil;
import org.apache.hadoop.hbase.mapreduce.TableMapper;
import org.apache.hadoop.hbase.mapreduce.TableReducer;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

import java.io.IOException;
import java.util.NavigableMap;
import java.util.Set;

/**
 * @author adam
 * @date 2022/6/10
 * 使用pagerank算法进行权重计算
 */
public class Step2_PageRank extends Configured implements Tool {

    /**
     * 1. 平铺自己所有的外连接
     * 2. 给自己一个默认的权重值
     * 3. 将自己的权重值平均分配给自己所有的外连接
     * 4. 对于没有外链的权重直接给0
     */
    public static class PageRankMapper extends TableMapper<Text, Text> {


        @Override
        //代码要复用第一次逻辑和之后的每一次逻辑不同
        //第一次数据从'clean_webpage'表获取 之后保存到'rank_result' 表
        protected void map(ImmutableBytesWritable key, Result value, Context context) throws IOException, InterruptedException {
            //将字节数组转化成字符串
            String keyStr = new String(key.get(), key.getOffset(), key.getLength());
            if (keyStr.contains(":http")){
                 keyStr = URLUtils.showUrl(keyStr);
            }

            //获取当前行中page列族里边oln的值  也就获取外链个数
            byte[] olnBytes = value.getValue("page".getBytes(), "oln".getBytes());
            int i = 0;
            if (olnBytes != null) {
                i = Bytes.toInt(olnBytes);
            }
            byte[] rankBytes = value.getValue("page".getBytes(), "rank".getBytes());
            //    设置网页默认的权重值  10
            double rank = 10;
            //如果不是第一次计算权重  那么就会有权重值
            if (rankBytes != null) {
                rank = Bytes.toDouble(rankBytes);
            }
            //   定义字符串  将来拼接每一个外链以及其权重值
            String outLinks = "";
            //有外链去拼接
            if (i > 0) {
                //获取列族ol的所有数据
                NavigableMap<byte[], byte[]> ols = value.getFamilyMap("ol".getBytes());
                //外链集合
                Set<byte[]> keySet = ols.keySet();
                double score = rank / keySet.size();
                //    拿到每一个外链 然后拼接他的权重
                for (byte[] bytes : keySet) {
                    String oLink = new String(bytes);
                    outLinks += oLink + ",";
                    context.write(new Text(oLink), new Text(String.valueOf(score) ));
                }
                //    去除最后拼接的一个逗号
                if (outLinks.endsWith(",")) {
                    outLinks = outLinks.substring(0, outLinks.length() - 1);
                }
                context.write(new Text(keyStr), new Text(outLinks));
            } else {
                //对于没有外链的  权重值给0
                context.write(new Text(keyStr), new Text(0 + ""));
            }
            //}

        }


    }

    public static class PageRankReducer extends TableReducer<Text, Text, NullWritable> {
        @Override
        //http://www.briup.com/index  [http://www.briup.com/index,http://www.briup.com/index,http://www.briup.com/index,http://www.briup.com/index,2,23,23,2]
        protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
            String uri = new String(key.getBytes(), 0, key.getLength()).trim();
            //    定义阻尼因子
            double d = 0.85;
            //    权重
            double sum = 0;
            //    如果values为空字符串不操作
            //    如果value包含http 表示这个value是记录当前连接与外链的关系  如果不包含 记录的是权重值
            //    将key恢复成nutch采集的数据形式
            //String uri = returnNutchKey(k);
            Put put = new Put(uri.getBytes());
            System.out.println(new String(uri.getBytes()));
            for (Text value : values) {
                String ctn = value.toString().trim();
                if (!ctn.equals("")) {
                    if (ctn.contains("http")) {
                        String[] split = ctn.split(",");
                        //外链个数
                        put.addColumn("page".getBytes(), "oln".getBytes(), Bytes.toBytes(split.length));
                        for (String s : split) {
                            put.addColumn("ol".getBytes(), s.getBytes(), "1".getBytes());
                        }

                    } else {
                        double v = Double.parseDouble(ctn);
                        sum += v;
                    }
                }
            }
            //嵌套公式
            double rank = sum * d + (1.0 - d);
            put.addColumn("page".getBytes(), "rank".getBytes(), Bytes.toBytes(rank));
            context.write(NullWritable.get(), put);

        }


    }

    @Override
    public int run(String[] args) throws Exception {
        Configuration conf = getConf();
        Job job = Job.getInstance(conf, "pageRank");
        job.setJarByClass(this.getClass());
        TableMapReduceUtil.initTableMapperJob("clean_webpage", new Scan(), PageRankMapper.class, Text.class, Text.class
                , job);
        TableMapReduceUtil.initTableReducerJob("rank_result", PageRankReducer.class, job);
        job.waitForCompletion(true);
        int i = 0;

        for (; i < 5; i++) {
            Configuration conf1 = getConf();
            Job job1 = Job.getInstance(conf1, "pageRank-item" + i);
            job1.setJarByClass(this.getClass());
            TableMapReduceUtil.initTableMapperJob("rank_result", new Scan(), PageRankMapper.class, Text.class, Text.class
                    , job1);
            TableMapReduceUtil.initTableReducerJob("rank_result", PageRankReducer.class, job1);
            job1.waitForCompletion(true) ;
        }
        return 1;

    }

    public static void main(String[] args) throws Exception {
        ToolRunner.run(new Step2_PageRank(), args);


    }


}
